<?php
namespace App\Model;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Equip extends BaseModel
{
    protected $connection = 'api';
    protected $table = 'equip';
    protected $equipTypeTable = 'equip_type';
    protected $userEquipTable = 'user_equip';
    protected $equipStreamTable = 'equip_stream';
    protected $equipShelveTable = 'equip_shelve';
    protected $userTable = 'user';
    protected $room_table = 'room';//房间表
    protected $union_room = 'union_room';//公会房间
    protected $union = 'union';//公会表

    protected $activityConn = 'activity';
    protected $equip_game_table = 'equip_game';
    protected $equip_notice_table = 'equip_notice';
    protected $equip_order_table = 'equip_order';
    protected $equip_order_draw_table = 'equip_order_draw';
    protected $equip_pool_one_table = 'equip_pool_one';
    protected $equip_pool_two_table = 'equip_pool_two';
    protected $equip_white_table = 'equip_white';
    protected $equip_white_config_table = 'equip_white_config';
    protected $equip_white_user_table = 'equip_white_user';
    protected $equip_auction_table = 'equip_auction';
    protected $adminEquipInfoTable = 'admin_equip_auction_config';//装备回收配置
    protected $userFinanceWalletTable = 'finance_wallet';//用户钱包
    protected $equipAuctionChatConfigTable = 'equip_auction_chat_config';//拍卖行公聊大厅配置
    protected $equipAuctionChatReportTable = 'equip_auction_chat_report';//拍卖行公聊厅举报列表

    protected $log = 'equip';//错误日志

    //装备列表
    public function equipList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $equip_id = $request->input('equip_id');
        $equip_type = $request->input('equip_type');
        $equip_sex = $request->input('equip_sex');
        $equip_level = $request->input('equip_level');

        $query = DB::connection($this->connection)->table($this->table);
        if(!empty($equip_id)) {
            $query = $query->where('equip_id', $equip_id);
        }
        if(!empty($equip_type)) {
            $query = $query->where('equip_type', $equip_type);
        }
        if(!empty($equip_sex)) {
            $query = $query->where('equip_sex', $equip_sex);
        }
        if(!empty($equip_level)) {
            $query = $query->where('equip_level', $equip_level);
        }
        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        if(!empty($result['data'])) {
            foreach($result['data'] as $key=>$val) {
                $val['small_image'] = build_image($val['small_image']);
                $val['image'] = build_image($val['image']);
                $result['data'][$key] = $val;
            }
        }

        return $result;
    }

    //获取装备类型
    public function getEquipType($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/getEquipType', $data, 'urlencoded', 'GET');
        return curlResultHandle($res);
    }

    //编辑装备
    public function editEquip($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/editEquip', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //装备货架列表
    public function equipShelveList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $equip_id = $request->input('equip_id');
        $equip_type = $request->input('equip_type');
        $equip_sex = $request->input('equip_sex');
        $equip_level = $request->input('equip_level');
        $shelve_name = $request->input('shelve_name');
        $equip_name = $request->input('equip_name');

        $query = DB::connection($this->connection)->table($this->equipShelveTable.' as a')
            ->join($this->table.' as b', "a.equip_id", "=", "b.equip_id")
            ->where('a.is_delete', 0)
            ->select(['a.id as shelve_id', 'a.equip_id', 'a.shelve_name', 'a.shelve_image', 'a.price_type', 'a.price', 'b.equip_name', 'b.equip_type', 'b.equip_sex', 'b.equip_level']);
        if(!empty($equip_id)) {
            $query = $query->where('a.equip_id', $equip_id);
        }
        if(!empty($equip_type)) {
            $query = $query->where('b.equip_type', $equip_type);
        }
        if(!empty($equip_sex)) {
            $query = $query->where('b.equip_sex', $equip_sex);
        }
        if(!empty($equip_level)) {
            $query = $query->where('b.equip_level', $equip_level);
        }
        if(!empty($shelve_name)) {
            $query = $query->where('a.shelve_name', 'like', '%'.$shelve_name.'%');
        }
        if(!empty($equip_name)) {
            $query = $query->where('b.equip_name', 'like', '%'.$equip_name.'%');
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        if(!empty($result['data'])) {
            foreach($result['data'] as $key=>$val) {
                $val['shelve_image'] = build_image($val['shelve_image']);
                $result['data'][$key] = $val;
            }
        }

        return $result;
    }

    //装备货架新增
    public function addEquipShelve($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/addEquipShelve', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //装备货架编辑
    public function editEquipShelve($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/editEquipShelve', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //装备货架删除
    public function delEquipShelve($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/delEquipShelve', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //编辑装备类型
    public function editEquipType($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/equip/editEquipType', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星游戏列表
    public function getGameList()
    {
        $list = DB::connection($this->activityConn)->table($this->equip_game_table)->get();
        $list = objToArray($list);

        return $list;
    }

    //开运装备星游戏配置修改
    public function gameEdit($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/gameEdit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星游戏开启/关闭
    public function gameStatus($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/gameStatus', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星一级奖池列表
    public function getPollOneList(Request $request)
    {
        $query = DB::connection($this->activityConn)->table($this->equip_pool_one_table)->where('is_delete', 0);
        if(!empty($request['game_id'])) {
            $query = $query->where('game_id', $request['game_id']);
        }

        $list = $query->get();
        $list = objToArray($list);
        if(empty($list)) {
            return [];
        }
        foreach($list as $key=>$val) {
            $list[$key]['item_img'] = build_image($val['item_img']);
        }

        return $list;
    }

    //开运装备星一级奖池新增
    public function pollOneAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollOneAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星一级奖池修改
    public function pollOneEdit($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollOneEdit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星一级奖池删除
    public function pollOneDel($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollOneDel', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星二级奖池列表
    public function getPollTwoList(Request $request)
    {
        $query = DB::connection($this->activityConn)
            ->table($this->equip_pool_two_table)
            ->where('is_delete', 0)
            ->where('pool_one_id', $request['pool_one_id']);
        $list = $query->get();
        $list = objToArray($list);
        if(empty($list)) {
            return [];
        }

        $gameList = DB::connection($this->activityConn)->table($this->equip_game_table)->get();
        $gameList = array_column(objToArray($gameList), null, 'game_id');

        $equipIds = array_merge(array_column($list, 'man_equip_id'),array_column($list, 'girl_equip_id'));
        $equipList = DB::connection($this->connection)->table($this->table)->whereIn('equip_id', $equipIds)->get();
        $equipList = array_column(objToArray($equipList), null, 'equip_id');

        foreach($list as $key=>$val) {
            $val['man_equip_name'] = empty($equipList[$val['man_equip_id']]['equip_name']) ? '' : $equipList[$val['man_equip_id']]['equip_name'];
            $val['girl_equip_name'] = empty($equipList[$val['girl_equip_id']]['equip_name']) ? '' : $equipList[$val['girl_equip_id']]['equip_name'];
            $val['game_name'] = empty($gameList[$val['game_id']]['game_name']) ? '' : $gameList[$val['game_id']]['game_name'];

            $list[$key] = $val;
        }

        return $list;
    }

    //开运装备星二级奖池新增
    public function pollTwoAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollTwoAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星二级奖池修改
    public function pollTwoEdit($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollTwoEdit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星二级奖池删除
    public function pollTwoDel($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/pollTwoDel', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单列表
    public function getWhiteList(Request $request)
    {
        $gameList = $this->getGameList();
        $gameList = array_column($gameList, null, 'game_id');

        $query = DB::connection($this->activityConn)->table($this->equip_white_table)->where('is_delete', 0);
        if(!empty($request['game_id'])) {
            $query = $query->where('game_id', $request['game_id']);
        }

        $list = $query->get();
        $list = objToArray($list);
        if(empty($list)) {
            return [];
        }

        foreach($list as $key=>$val) {
            $val['gameName'] = empty($gameList[$val['game_id']]['game_name']) ? '' : $gameList[$val['game_id']]['game_name'];
            //白名单用户
            $val['white_user'] = [];
            $whiteUserList = DB::connection($this->activityConn)->table($this->equip_white_user_table)->where('white_id', $val['id'])->where('is_delete', 0)->get();
            $whiteUserList = objToArray($whiteUserList);
            if(!empty($whiteUserList)) {
                $userIds = array_column($whiteUserList, 'user_id');
                $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
                $userList = array_column(objToArray($userList), null, 'user_id');
                foreach($whiteUserList as $v2) {
                    $val['white_user'][] = [
                        'user_id' => $v2['user_id'],
                        'nickname' => empty($userList[$v2['user_id']]['nickname']) ? '' : $userList[$v2['user_id']]['nickname'],
                        'uuid' => empty($userList[$v2['user_id']]['uuid']) ? '' : $userList[$v2['user_id']]['uuid'],
                    ];
                }
            }

            $list[$key] = $val;
        }

        return $list;
    }

    //开运装备星白名单新增
    public function whiteAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单修改
    public function whiteEdit($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteEdit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单删除
    public function whiteDelete($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteDelete', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单配置列表
    public function getWhiteConfigList(Request $request)
    {
        $gameList = $this->getGameList();
        $gameList = array_column($gameList, null, 'game_id');

        $query = DB::connection($this->activityConn)->table($this->equip_white_config_table.' as a')
            ->leftJoin($this->equip_white_table.' as b' ,'a.white_id','=','b.id')
            ->select("a.*", "b.game_id")
            ->where('a.is_delete', 0);
        if(!empty($request['white_id'])) {
            $query = $query->where('a.white_id', $request['white_id']);
        }

        $list = $query->get();
        $list = objToArray($list);
        if(empty($list)) {
            return [];
        }

        //二级奖池
        $pollTwoIds = [];
        foreach($list as $key=>$val) {
            $val['white_reward'] = json_decode($val['white_reward'], true);
            $pollTwoIds = array_merge($pollTwoIds, array_column($val['white_reward'], 'pollTwoId'));
            $list[$key] = $val;
        }
        $pollTwoList = DB::connection($this->activityConn)->table($this->equip_pool_two_table)->whereIn('id', $pollTwoIds)->get();
        $pollTwoList = array_column(objToArray($pollTwoList), null, 'id');
        //装备信息
        $equipIds = array_merge(array_column($pollTwoList, 'man_equip_id'),array_column($pollTwoList, 'girl_equip_id'));
        $equipList = DB::connection($this->connection)->table($this->table)->whereIn('equip_id', $equipIds)->get();
        $equipList = array_column(objToArray($equipList), null, 'equip_id');

        foreach($list as $key=>$val) {
            $val['gameName'] = empty($gameList[$val['game_id']]['game_name']) ? '' : $gameList[$val['game_id']]['game_name'];
            foreach($val['white_reward'] as $k2=>$v2) {
                $v2['man_equip_id'] = 0;
                $v2['man_equip_name'] = '';
                $v2['girl_equip_id'] = 0;
                $v2['girl_equip_name'] = '';
                if(!empty($pollTwoList[$v2['pollTwoId']])) {
                    $poolTwo = $pollTwoList[$v2['pollTwoId']];
                    $v2['man_equip_id'] = $poolTwo['man_equip_id'];
                    $v2['man_equip_name'] = empty($equipList[$v2['man_equip_id']]['equip_name']) ? '' : $equipList[$v2['man_equip_id']]['equip_name'];
                    $v2['girl_equip_id'] = $poolTwo['girl_equip_id'];
                    $v2['girl_equip_name'] = empty($equipList[$v2['girl_equip_id']]['equip_name']) ? '' : $equipList[$v2['girl_equip_id']]['equip_name'];
                }

                $val['white_reward'][$k2] = $v2;
            }

            $list[$key] = $val;
        }

        return $list;
    }

    //开运装备星白名单配置新增
    public function whiteConfigAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteConfigAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单配置删除
    public function whiteConfigDelete($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteConfigDelete', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单用户列表
    public function getWhiteUserList(Request $request)
    {
        $gameList = $this->getGameList();
        $gameList = array_column($gameList, null, 'game_id');

        $query = DB::connection($this->activityConn)->table($this->equip_white_user_table)
            ->where('is_delete', 0)
            ->where('white_id', $request['white_id']);

        $list = $query->get();
        $list = objToArray($list);
        if(empty($list)) {
            return [];
        }

        $userIds = array_column($list, 'user_id');
        $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->get();
        $userList = array_column(objToArray($userList), null, 'user_id');

        foreach($list as $key=>$val) {
            $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
            $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];

            $list[$key] = $val;
        }

        return $list;
    }

    //开运装备星白名单用户新增
    public function whiteUserAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteUserAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星白名单用户删除
    public function whiteUserDelete($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/equip/whiteUserDelete', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //开运装备星统计数据概述
    public function statSearchAll(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $game_id = $request->input('game_id');

        $query1 = DB::connection($this->activityConn)->table($this->equip_order_table);
        if(!empty($date_st)) {
            $query1 = $query1->where('created_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query1 = $query1->where('created_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        if(!empty($game_id)) {
            $query1 = $query1->where('game_id', $game_id);
        }
        $res1 = $query1->selectRaw("count(DISTINCT user_id) as userNum, sum(price_total) as price_total, sum(reward_jd_num) as reward_jd_num")
                        ->first();
        $res1 = objToArray($res1);


        $query2 = DB::connection($this->activityConn)->table($this->equip_auction_table)->where('sale_status', 5);
        if(!empty($date_st)) {
            $query2 = $query2->where('buy_time', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('buy_time', '<=', $date_ed);
        }
        $res2 = $query2->selectRaw("sum(price) as auctionNum")
                        ->first();
        $res2 = objToArray($res2);

        $result = [];
        //人数
        $result['userNum'] = (int) $res1['userNum'];
        //消耗金豆数
        $result['payNum'] = (int) $res1['price_total'];
        //抽奖产出金豆数
        $result['getNum'] = (int) $res1['reward_jd_num'];
        //系统回收金豆数
        $result['auctionNum'] = (int) $res2['auctionNum'];
        //利润金豆
        $result['profitNum'] = $result['payNum'] - $result['getNum'];
        //利润率
        $result['profiRate'] = empty($result['payNum']) ? 0 : round(($result['profitNum']/$result['payNum'])*100, 2);

        return $result;
    }

    //开运装备星指定用户挑战记录
    public function userDrawList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $game_id = $request->input('game_id');
        $user_id = $request->input('user_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $gameList = DB::connection($this->activityConn)->table($this->equip_game_table)->get();
        $gameList = array_column(objToArray($gameList), null, 'game_id');

        $poolOneList = DB::connection($this->activityConn)->table($this->equip_pool_one_table)->get();
        $poolOneList = array_column(objToArray($poolOneList), null, 'id');

        $poolTwoList = DB::connection($this->activityConn)->table($this->equip_pool_two_table)->get();
        $poolTwoList = array_column(objToArray($poolTwoList), null, 'id');

        $equipList = DB::connection($this->connection)->table($this->table)->get();
        $equipList = array_column(objToArray($equipList), null, 'equip_id');

        $query = DB::connection($this->activityConn)->table($this->equip_order_table);
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        if(!empty($game_id)) {
            $query = $query->where('game_id', $game_id);
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $result = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);

        if(!empty($result['data'])) {
            $userIds = array_column($result['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');
        }

        $list = [];
        foreach($result['data'] as $val) {
            //抽奖记录
            $drawList = DB::connection($this->activityConn)->table($this->equip_order_draw_table)->where('order_id', $val['id'])->get();
            $drawList = objToArray($drawList);

            $orderInfo = [];
            //订单ID
            $orderInfo['order_id'] = $val['id'];
            //游戏
            $orderInfo['game_id'] = $val['game_id'];
            $orderInfo['game_name'] = empty($gameList[$orderInfo['game_id']]['game_name']) ? '' : $gameList[$orderInfo['game_id']]['game_name'];
            //用户
            $orderInfo['user_id'] = $val['user_id'];
            $orderInfo['nickname'] = empty($userList[$orderInfo['user_id']]['nickname']) ? '' : $userList[$orderInfo['user_id']]['nickname'];
            $orderInfo['uuid'] = empty($userList[$orderInfo['user_id']]['uuid']) ? '' : $userList[$orderInfo['user_id']]['uuid'];
            //总挑战次数
            $orderInfo['drawNum'] = (int) $val['num'];
            //奖励价值金豆数
            $orderInfo['reward_jd_num'] = (int) $val['reward_jd_num'];
            //时间
            $orderInfo['created_at'] = strtotime($val['created_at']);
            //抽奖记录
            $orderInfo['logs'] = [];
            $i = 1;
            foreach($drawList as $v2) {
                $item = [];
                //当前挑战序号
                $item['i'] = $i;
                //装备ID
                $item['equip_id'] = (int) $v2['equip_id'];
                //装备名称
                $item['equip_name'] = empty($equipList[$item['equip_id']]['equip_name']) ? '' : $equipList[$item['equip_id']]['equip_name'];
                //一级奖池id
                $item['pool_one_id'] = (int) $v2['pool_one_id'];
                //一级奖池名称
                $item['pool_one_name'] = empty($poolOneList[$item['pool_one_id']]['item_name']) ? '' : $poolOneList[$item['pool_one_id']]['item_name'];
                //二级奖池id
                $item['pool_two_id'] = (int) $v2['pool_two_id'];
                //奖励价值金豆数
                $item['reward_jd_num'] = (int) $v2['reward_jd_num'];
                //是否是白名单奖池
                $item['if_white'] = (int) $v2['if_white'];
                //一级奖池概率类型 0=无 1=基础概率 2=低回概率 3=高回概率 4=新人保护概率 5=每日保护概率1 6=每日保护概率2
                $item['rate_type'] = (int) $v2['rate_type'];

                $orderInfo['logs'][] = $item;
                $i++;
            }
            $list[] = $orderInfo;
        }
        $result['data'] = $list;

        return $result;
    }

    //开运装备星奖励产出查询
    public function statPoolItem(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $game_id = $request->input('game_id');
        $pool_one_id = $request->input('pool_one_id');

        $gameList = DB::connection($this->activityConn)->table($this->equip_game_table)->get();
        $gameList = array_column(objToArray($gameList), null, 'game_id');

        $poolOneList = DB::connection($this->activityConn)->table($this->equip_pool_one_table)->get();
        $poolOneList = array_column(objToArray($poolOneList), null, 'id');

        $query1 = DB::connection($this->activityConn)->table($this->equip_order_draw_table);
        if(!empty($date_st)) {
            $query1 = $query1->where('created_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query1 = $query1->where('created_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        if(!empty($game_id)) {
            $query1 = $query1->where('game_id', $game_id);
        }
        if(!empty($pool_one_id)) {
            $query1 = $query1->where('pool_one_id', $pool_one_id);
        }
        $data = $query1->selectRaw("count(1) as itemNum, sum(reward_jd_num) as reward_jd_num, pool_one_id, game_id")
                    ->groupBy('pool_one_id','game_id')
                    ->get();
        $data = objToArray($data);

        $list = [];
        $count = array_sum(array_column($data, 'itemNum'));
        foreach($data as $val) {
            $item = [];
            //游戏
            $item['game_id'] = $val['game_id'];
            $item['game_name'] = empty($gameList[$item['game_id']]['game_name']) ? '' : $gameList[$item['game_id']]['game_name'];
            //一级奖池id
            $item['pool_one_id'] = (int) $val['pool_one_id'];
            //一级奖池名称
            $item['pool_one_name'] = empty($poolOneList[$item['pool_one_id']]['item_name']) ? '' : $poolOneList[$item['pool_one_id']]['item_name'];
            //数量
            $item['itemNum'] = (int) $val['itemNum'];
            //当前概率
            $item['rate'] = round(($val['itemNum']/$count)*100, 2);
            //产出价值
            $item['reward_jd_num'] = (int) $val['reward_jd_num'];

            $list[] = $item;
        }
        $orderBy1 = array_column($list, 'game_id');
        $orderBy2 = array_column($list, 'pool_one_id');
        array_multisort($orderBy1, SORT_DESC, $orderBy2, SORT_ASC, $list);

        $result['data'] = $list;

        return $result;
    }

    //开运装备星奖励产出详情查询
    public function statPoolItemDetail(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $pool_one_id = $request->input('pool_one_id');
        if(empty($pool_one_id)) {
            return [
                'code' => 50000,
                'msg' => '一级奖池id不可为空',
            ];
        }

        $equipList = DB::connection($this->connection)->table($this->table)->get();
        $equipList = array_column(objToArray($equipList), null, 'equip_id');

        $query1 = DB::connection($this->activityConn)->table($this->equip_order_draw_table);
        $query1 = $query1->where('pool_one_id', $pool_one_id);
        if(!empty($date_st)) {
            $query1 = $query1->where('created_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query1 = $query1->where('created_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        $data = $query1->selectRaw("count(1) as itemNum, sum(reward_jd_num) as reward_jd_num, equip_id")
                    ->groupBy('equip_id')
                    ->get();
        $data = objToArray($data);

        $list = [];
        $count = array_sum(array_column($data, 'itemNum'));
        foreach($data as $val) {
            $item = [];
            //装备ID
            $item['equip_id'] = (int) $val['equip_id'];
            //装备名称
            $item['equip_name'] = empty($equipList[$item['equip_id']]['equip_name']) ? '' : $equipList[$item['equip_id']]['equip_name'];
            //数量
            $item['itemNum'] = (int) $val['itemNum'];
            //产出价值
            $item['reward_jd_num'] = (int) $val['reward_jd_num'];
            //当前概率
            $item['rate'] = round(($val['itemNum']/$count)*100, 2);

            $list[] = $item;
        }
        $orderBy1 = array_column($list, 'equip_id');
        array_multisort($orderBy1, SORT_ASC);

        $result['data'] = $list;

        return $result;
    }

    //开运装备星用户参与排行
    public function statUserOrder(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $game_id = $request->input('game_id');

        $query1 = DB::connection($this->activityConn)->table($this->equip_order_table);
        if(!empty($date_st)) {
            $query1 = $query1->where('created_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query1 = $query1->where('created_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        if(!empty($game_id)) {
            $query1 = $query1->where('game_id', $game_id);
        }
        $res1 = $query1->selectRaw("sum(price_total) as price_total, sum(reward_jd_num) as reward_jd_num, user_id")
                    ->groupBy('user_id')
                    ->get();
        $res1 = objToArray($res1);
        $res1 = array_column($res1, null, 'user_id');

        $query2 = DB::connection($this->activityConn)->table($this->equip_auction_table)->where('sale_status', 5);
        if(!empty($date_st)) {
            $query2 = $query2->where('updeated_at', '>=', date("Y-m-d H:i:s", $date_st));
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('updeated_at', '<=', date("Y-m-d H:i:s", $date_ed));
        }
        $res2 = $query2->selectRaw("user_id,sum(price) as auctionNum")
                    ->groupBy('user_id')
                    ->get();
        $res2 = objToArray($res2);
        $res2 = array_column($res2, null, 'user_id');

        $userIds = array_unique(array_merge(array_column($res1,'user_id'),array_column($res2,'user_id')));
        $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
        $userList = array_column(objToArray($userList), null, 'user_id');

        $list = [];
        foreach($userIds as $userId) {
            if(isset($list[$userId])) {
                continue;
            }

            $item = [];
            //用户
            $item['user_id'] = $userId;
            $item['nickname'] = empty($userList[$userId]['nickname']) ? '' : $userList[$userId]['nickname'];
            $item['uuid'] = empty($userList[$userId]['uuid']) ? '' : $userList[$userId]['uuid'];
            //消耗金豆数量
            $item['payNum'] = empty($res1[$userId]['price_total']) ? 0 : (int) $res1[$userId]['price_total'];
            //产出金豆数量
            $item['getNum'] = empty($res1[$userId]['reward_jd_num']) ? 0 : (int) $res1[$userId]['reward_jd_num'];
            //利润金豆数量
            $item['profitNum'] = $item['getNum'] + $item['payNum'];
            //拍卖行回收金豆数量
            $item['auctionNum'] = empty($res2[$userId]['auctionNum']) ? 0 : (int) $res2[$userId]['auctionNum'];

            $list[] = $item;
        }

        return $list;
    }

    //拍卖行装备售卖情况
    public function getEquipAuctionList($page, $limit, $sale_status, $start_time, $end_time, $equipType, $saleUid, $unUid){
        //数据查询
        $where = function($q)use($sale_status, $start_time, $end_time, $equipType, $saleUid, $unUid) {
            if (!empty($sale_status)) {
                if($sale_status == 2){
                    $q->whereIn('sale_status',[2,5]);
                }elseif($sale_status == 3){
                    $q->whereIn('sale_status',[3,4]);
                }else{
                    $q->where('sale_status',$sale_status);
                }
            }
            //开始时间
            if(!empty($start_time) && empty($end_time)){
                $q->where("sale_time",'>=',$start_time);
            }
            //结束时间
            if(!empty($end_time) && empty($start_time)){
                $q->where("sale_time",'<=',$end_time);
            }
            if(!empty($end_time) && !empty($start_time)){
                $q->where("sale_time",'>=',$start_time);
                $q->where("sale_time",'<=',$end_time);
            }

            //出售用户
            if(!empty($saleUid)){
                $userInfo = DB::connection($this->connection)->table($this->userTable)->where('uuid',$saleUid)->first(['user_id']);
                $userInfo = objToArray($userInfo);
                $saleUserId = !empty($userInfo) ? $userInfo['user_id'] : 0;
                $q->where('user_id',$saleUserId);
            }

            //公会长
            if(!empty($unUid)){
                $userInfo = DB::connection($this->connection)->table($this->userTable)->where('uuid',$unUid)->first(['user_id']);
                $userInfo = objToArray($userInfo);
                $unUserId = !empty($userInfo) ? $userInfo['user_id'] : 0;
                
                //查询公会
                $uninfo = DB::connection($this->connection)->table($this->union)->where('un_user_id',$unUserId)->first(['id']);
                $uninfo = objToArray($uninfo);

                //查询公会房间
                $unionRoom = DB::connection($this->connection)->table($this->union_room)->where('un_id',$uninfo['id'])->get(['room_id']);
                $unionRoom = objToArray($unionRoom);
                $roomList = array_column($unionRoom,'room_id');
                $q->whereIn('room_id',$roomList);
            }

            //装备类型
            if(!empty($equipType)){
                $equipIds = DB::connection($this->connection)->table($this->table)->where('equip_type',$equipType)->get(['equip_id']);
                $equipIds = objToArray($equipIds);
                $equipIds = array_column($equipIds,'equip_id');
                $q->whereIn("equip_id",$equipIds);
            }
        };
        //先查询符合条件的装备表中的id
        $equipAtuctionRes = DB::connection($this->connection)->table($this->equip_auction_table)->where($where)->orderBy('sale_status','ASC')->orderBy('buy_time','DESC')->paginate($limit,['*'],'page',$page);
        $equipAtuctionRes = objToArray($equipAtuctionRes);

        if(empty($equipAtuctionRes)){
            return [];
        }

        if(!empty($equipAtuctionRes['data']))
        {
            $auctionIds = array_column($equipAtuctionRes['data'],'equip_id');
            //装备数据
            $equipInfos = DB::connection($this->connection)->table($this->table)->whereIn('equip_id',$auctionIds)->get(['equip_id','equip_name','small_image','equip_level','equip_type']);
            $equipInfos = objToArray($equipInfos);
            $equipInfos = array_column($equipInfos,null,'equip_id');
            //装备类型名称
            $equipTyeInfos = DB::connection($this->connection)->table($this->equipTypeTable)->get();
            $equipTyeInfos = objToArray($equipTyeInfos);
            $equipTyeInfos = array_column($equipTyeInfos,null,'id');
            //用户
            $userArr = DB::connection($this->connection)->table($this->userTable)->get(['user_id','nickname','uuid']);
            $userArr = objToArray($userArr);
            $userArr = array_column($userArr,null,'user_id');
            //房间信息
            //查询房间拥有者
            $roomInfo = DB::connection($this->connection)->table($this->room_table)->where('business_type',1)->get(['user_id','name','room_id']);
            $roomInfo = objToArray($roomInfo);
            $roomUserIds = array_column($roomInfo,'user_id');
            $roomInfo = array_column($roomInfo,null,'room_id');
        
            //公会信息
            $unionInfos = DB::connection($this->connection)->table($this->union)->whereIn('un_user_id',$roomUserIds)->get(['un_user_id','name']);
            $unionInfos = objToArray($unionInfos);
            $unionInfos = array_column($unionInfos,null,'un_user_id');

            foreach($equipAtuctionRes['data'] as $k=>$v){
                $newData[$k]['auction_id'] = $v['auction_id'];//订单id
                $newData[$k]['equip_type_name'] = $equipTyeInfos[$equipInfos[$v['equip_id']]['equip_type']]['name'] ?? '';//装备类型名称
                $newData[$k]['equip_id'] = $v['equip_id'];//装备id
                $newData[$k]['equip_name'] = $equipInfos[$v['equip_id']]['equip_name']; //装备名称
                $newData[$k]['equip_price'] = $v['price'];//装备出售金豆价格

                $newData[$k]['sale_user_name'] = $userArr[$v['user_id']]['nickname'] ?? '';//出售用户名称
                $newData[$k]['sale_user_uuid'] = $userArr[$v['user_id']]['uuid'] ?? '';//出售用户UUID
                $newData[$k]['buy_user_uuid'] = 0;//购买用户UUID
                $newData[$k]['buy_user_name'] ='';//购买用户名称
                $newData[$k]['union_user_name'] = '';//公会长用户名称
                $newData[$k]['union_user_uuid'] = 0;//公会长UUID
                $newData[$k]['union_name'] = '';//公会名称
                if(!empty($v['buy_user_id'])){
                    $newData[$k]['buy_user_uuid'] = $userArr[$v['buy_user_id']]['uuid'] ?? '';//购买用户UUID
                    $newData[$k]['buy_user_name'] = $userArr[$v['buy_user_id']]['nickname'] ?? '';//购买用户名称
                }

                if(!empty($v['room_id']) && isset($roomInfo[$v['room_id']])){
                    $newData[$k]['union_user_name'] = $userArr[$roomInfo[$v['room_id']]['user_id']]['nickname'] ?? '';//公会长用户名称
                    $newData[$k]['union_user_uuid'] = $userArr[$roomInfo[$v['room_id']]['user_id']]['uuid'] ?? '';//公会长UUID
                    $newData[$k]['union_name'] = $unionInfos[$roomInfo[$v['room_id']]['user_id']]['name'] ?? '';//公会名称
                }
                
                
                if(in_array($v['sale_status'],[2,5])){
                    $newData[$k]['sale_status'] = 2;
                }elseif(in_array($v['sale_status'],[3,4])){
                    $newData[$k]['sale_status'] = 3;
                }else{
                    $newData[$k]['sale_status'] = $v['sale_status'];//1=出售中 2=已出售 3=用户下架 4=运营下架 5=系统回收
                } 
            }
            $equipAtuctionRes['data'] = $newData;
        }
        return $equipAtuctionRes;
    }
    
    //拍卖数据统计
    public function getEquipAuctionStatistic(){
        $res = DB::connection($this->connection)->table($this->equip_auction_table)
               ->select(DB::raw('COUNT(*) as allcount,COUNT(sale_status = 1 or null) as onsale,COUNT(sale_status = 3 or sale_status = 4  or null) as unsale,COUNT(sale_status = 2 or sale_status = 5 or  null) as buynums,SUM(jd_complete_value) as completeJd,SUM(jd_commission_value) as rateJd,SUM(jd_union_value) as unionJd,SUM(jd_system_value) as sysJd'))->get();
        return $res;
    }

    //后台下架拍卖
    public function unSaleAuction($auctionId){
        //拍卖详情
        $auctionInfo = DB::connection($this->connection)->table($this->equip_auction_table)->where('auction_id',$auctionId)->first();
        $auctionInfo = objToArray($auctionInfo);
        if(empty($auctionInfo)){
            return ['code'=>'-1','data'=>[],'msg'=>'拍卖记录不存在'];
        }
        //是否已经出售
        if($auctionInfo['sale_status'] == 2){
            return ['code'=>'-1','data'=>[],'msg'=>'装备已出售'];
        }
        $data['sale_status'] = 4;//后台下架
        $data['unsale_time'] = date('Y-m-d H:i:s',time());
        $data['updeated_at'] = date('Y-m-d H:i:s',time());
        $status = DB::connection($this->connection)->table($this->equip_auction_table)->where('auction_id',$auctionId)->update($data);
        if($status){
            //归还用户装备
            $param=[
                [
                    'user_id'=>$auctionInfo['user_id'],
                    'equip_id'=>$auctionInfo['equip_id'],//装备id
                    'num'=>1,//归还数量
                    'equip_type' => 4,//拍卖下架
                    'data_id' => $auctionInfo['auction_id']//拍卖id
                ]
            ];
            $params['equip_list']= json_encode($param,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $result = curl_request(env('KKAUDIO_API') . '/inner/equip/sendEquipToUser', $params, 'urlencoded', 'POST');
            write_log($this->log,'赠送装备结果:',$result);
            return ['code'=>'0','data'=>[],'msg'=>'ok'];
        }else{
            return ['code'=>'1','data'=>[],'msg'=>'ok'];;
        }
        
        
    }

    //拍卖行-回收系统配置
    public function equipSysConfig(){
        $list = DB::connection($this->connection)->table($this->adminEquipInfoTable)
                ->leftJoin($this->userFinanceWalletTable,'admin_equip_auction_config.user_id','finance_wallet.user_id')
                ->get();
        $list = objToArray($list);        
        return $list;
    }

    //拍卖行-禁用系统回收用户
    public function updateSysConfig($status, $id){
        $params = [
            'id' => $id,
            'status' => $status
        ];
        $result = curl_request(env('KKAUDIO_API') . '/inner/equip/equipsyschange', $params, 'urlencoded', 'POST');
        write_log($this->log,'更改系统回收用户结果:',$result);
        return ['code'=>'0','data'=>[],'msg'=>'ok'];
    }

    //拍卖行-后台-新增回收用户
    public function AddSysConfig($user_id,$minutes){
        $params = [
            'user_id' => $user_id,
            'minutes' => $minutes
        ];
        $result = curl_request(env('KKAUDIO_API') . '/inner/equip/addsyschange', $params, 'urlencoded', 'POST');
        write_log($this->log,'新增回收用户结果:',$result);
        return ['code'=>'0','data'=>[],'msg'=>'ok'];
    }

    //拍卖行-后台-增加系统回收用户金豆数
    public function equipAuctionAddSysUserJd($id,$nums){
        $info = DB::connection($this->connection)->table($this->adminEquipInfoTable)->where('id',$id)->first();
        $info = objToArray($info); 
        if(empty($info)){
            return ['code'=>'-1','data'=>[],'msg'=>'配置不存在'];
        }
        $params = [
            'userid' => $info['user_id'],
            'dataid' => $info['id'],
            'price' => $nums,
        ];
        $result = curl_request(env('KKAUDIO_API') . '/inner/equip/addequipsysjd', $params, 'urlencoded', 'POST');
        write_log($this->log,'增加金豆回收用户结果:',$result);
        return ['code'=>'0','data'=>[],'msg'=>'ok'];
    }

    //拍卖行-后台-增加修改公聊内容
    public function equipAuctionChangeChatConfig($id, $mic_all_time, $min_rich_value, $max_rich_value, $min_charm_value, $max_charm_value, $min_user_rich_value, $max_user_rich_value, $min_user_recharge_value,$max_user_recharge_value,$after_day,$status){
        $params = [
            'id' => $id,
            'mic_all_time' => $mic_all_time,
            'min_rich_value' =>$min_rich_value,
            'max_rich_value' => $max_rich_value,
            'min_charm_value' => $min_charm_value,
            'max_charm_value' => $max_charm_value,
            'min_user_rich_value' => $min_user_rich_value,
            'max_user_rich_value' => $max_user_rich_value,
            'min_user_recharge_value' => $min_user_recharge_value,
            'max_user_recharge_value' => $max_user_recharge_value,
            'after_day' => $after_day,
            'status' => $status
        ];
        $result = curl_request(env('KKAUDIO_API') . '/inner/equip/change_equip_auction_chatconfig', $params, 'json', 'POST');
        return ['code'=>'0','data'=>[],'msg'=>'ok'];
    }

    //拍卖行-后台-公聊配置类表
    public function equipAuctionChangeChatList($page, $limit){
        $list = DB::connection($this->connection)->table($this->equipAuctionChatConfigTable)->paginate($limit,['*'],'page',$page);
        return $list;
    }

    //公聊大厅举报列表
    public function equipAuctionChatReport($page, $limit, $date, $user_id, $user_name){
        $where = function($q)use($date, $user_id, $user_name) {
            if(!empty($date)){
                $date = strtotime($date);
                $startDate = Carbon::parse(date('y-m-d H:i:s',$date))->startOfDay()->toDateTimeString();
                $endDate = Carbon::parse(date('y-m-d H:i:s',$date))->endOfDay()->toDateTimeString();
                $q->where('created_at','>=',$startDate);
                $q->where('created_at','<=',$endDate);
            }
            if(!empty($user_id)){
                $q->where('user_id',$user_id);
            }
            if(!empty($user_name)){
                $userIds = DB::connection($this->connection)->table($this->userTable)->where('nickname','like',$user_name.'%')->get(['user_id']);
                $userIds = objToArray($userIds);
                $userIds = array_column($userIds,'user_id');
                $q->whereIn('user_id',$userIds);
            }
        };
        $list = DB::connection($this->connection)->table($this->equipAuctionChatReportTable)->where($where)->paginate($limit,['*'],'page',$page);
        $list = objToArray($list);
        if(!empty($list['data'])){
            foreach($list['data'] as $k=>$v){
                //发起人信息
                $userInfo = DB::connection($this->connection)->table($this->userTable)->where('user_id',$v['user_id'])->first();
                $userInfo = objToArray($userInfo);
                $list['data'][$k]['user_name'] = $userInfo['nickname'];
                $list['data'][$k]['user_uuid'] = $userInfo['uuid'];
                //被举报人信息
                $toUserInfo = DB::connection($this->connection)->table($this->userTable)->where('user_id',$v['report_userid'])->first();
                $toUserInfo = objToArray($toUserInfo);
                $list['data'][$k]['report_user_name'] = $toUserInfo['nickname'];
                $list['data'][$k]['report_uuid'] = $toUserInfo['uuid'];
            }
        }
        return $list;
    }

    //处理举报
    public function equipAuctionChatReportChange($id, $type, $time, $admin_id){
        $params = [
            'id' => $id,
            'type' => $type,
            'time' => $time,
            'admin_id' => $admin_id
        ];
        $result = curl_request(env('KKAUDIO_API') . '/inner/equip/equip_auction_report', $params, 'json', 'POST');
        write_log('equip_auction_chatreport','INFO 处理结果',['res'=>$result,'param'=>$params]);
        return ['code'=>'0','data'=>[],'msg'=>'ok'];
    }
}
